<template>
  <div class="chart-settings-container">
    <a-form layout="vertical">
      <!-- 基本设置 -->
      <a-form-item label="图表标题">
        <a-input v-model:value="localOptions.title.text" placeholder="请输入图表标题" @change="emitUpdate" />
      </a-form-item>
      
      <!-- 坐标轴设置 -->
      <a-divider>坐标轴设置</a-divider>
      
      <a-form-item label="X轴名称">
        <a-input v-model:value="localOptions.xAxis.name" placeholder="请输入X轴名称" @change="emitUpdate" />
      </a-form-item>
      
      <a-form-item label="Y轴名称">
        <a-input v-model:value="localOptions.yAxis.name" placeholder="请输入Y轴名称" @change="emitUpdate" />
      </a-form-item>
      
      <a-form-item label="类目数据">
        <a-textarea 
          v-model:value="categoriesText" 
          :rows="3" 
          placeholder="请输入类目数据，多个值用逗号分隔"
          @change="updateCategories"
        />
      </a-form-item>
      
      <!-- 图例设置 -->
      <a-divider>图例设置</a-divider>
      
      <a-form-item label="显示图例">
        <a-switch v-model:checked="localOptions.legend.show" @change="emitUpdate" />
      </a-form-item>
      
      <a-form-item label="图例位置">
        <a-radio-group v-model:value="localOptions.legend.orient" @change="emitUpdate">
          <a-radio-button value="horizontal">水平</a-radio-button>
          <a-radio-button value="vertical">垂直</a-radio-button>
        </a-radio-group>
      </a-form-item>
      
      <!-- 系列设置 -->
      <a-divider>数据系列</a-divider>
      
      <a-collapse v-model:activeKey="activeSeriesKeys">
        <a-collapse-panel 
          v-for="(series, index) in localOptions.series" 
          :key="'series-' + index"
          :header="`数据系列 ${index + 1}: ${series.name || '未命名'}`"
        >
          <a-form-item label="系列名称">
            <a-input v-model:value="series.name" placeholder="请输入系列名称" @change="updateSeriesData" />
          </a-form-item>
          
          <a-form-item label="系列数据">
            <a-textarea 
              v-model:value="seriesDataText[index]" 
              :rows="3" 
              placeholder="请输入数据值，多个值用逗号分隔"
              @change="() => updateSeriesData(index)"
            />
          </a-form-item>
          
          <a-form-item label="柱条颜色">
            <a-input 
              v-model:value="series.itemStyle.color" 
              type="color"
              style="width: 100px" 
              @change="emitUpdate" 
            />
          </a-form-item>
          
          <a-form-item label="显示标签">
            <a-switch v-model:checked="series.label.show" @change="emitUpdate" />
          </a-form-item>
          
          <a-form-item label="标签位置">
            <a-select v-model:value="series.label.position" style="width: 100%" @change="emitUpdate">
              <a-select-option value="inside">内部</a-select-option>
              <a-select-option value="outside">外部</a-select-option>
              <a-select-option value="right">右侧</a-select-option>
            </a-select>
          </a-form-item>
          
          <a-button 
            type="primary" 
            danger 
            @click="removeSeries(index)"
            style="margin-top: 10px"
          >
            删除此系列
          </a-button>
        </a-collapse-panel>
      </a-collapse>
      
      <a-button type="dashed" block @click="addSeries" style="margin-top: 16px">
        <plus-outlined /> 添加数据系列
      </a-button>
      
      <!-- 网格设置 -->
      <a-divider>网格设置</a-divider>
      
      <a-form-item label="上边距">
        <a-input-number 
          v-model:value="localOptions.grid.top" 
          :min="0" 
          :max="100" 
          style="width: 100%"
          @change="emitUpdate" 
        />
      </a-form-item>
      
      <a-form-item label="右边距">
        <a-input-number 
          v-model:value="localOptions.grid.right" 
          :min="0" 
          :max="100" 
          style="width: 100%"
          @change="emitUpdate" 
        />
      </a-form-item>
      
      <a-form-item label="下边距">
        <a-input-number 
          v-model:value="localOptions.grid.bottom" 
          :min="0" 
          :max="100" 
          style="width: 100%"
          @change="emitUpdate" 
        />
      </a-form-item>
      
      <a-form-item label="左边距">
        <a-input-number 
          v-model:value="localOptions.grid.left" 
          :min="0" 
          :max="100" 
          style="width: 100%"
          @change="emitUpdate" 
        />
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';

const props = defineProps({
  options: {
    type: Object,
    required: true
  }
});

const emit = defineEmits(['update:options']);

// 本地存储options，用于编辑
const localOptions = ref<any>({
  title: {
    text: '水平条形图'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  legend: {
    show: true,
    orient: 'horizontal',
    data: ['系列1', '系列2']
  },
  grid: {
    left: 40,
    right: 20,
    bottom: 30,
    top: 60
  },
  xAxis: {
    type: 'value',
    name: '数值'
  },
  yAxis: {
    type: 'category',
    name: '类目',
    data: ['类目1', '类目2', '类目3', '类目4', '类目5']
  },
  series: [
    {
      name: '系列1',
      type: 'bar',
      data: [18, 23, 29, 15, 25],
      label: {
        show: false,
        position: 'right'
      },
      itemStyle: {
        color: '#5470c6'
      }
    },
    {
      name: '系列2',
      type: 'bar',
      data: [12, 15, 30, 20, 18],
      label: {
        show: false,
        position: 'right'
      },
      itemStyle: {
        color: '#91cc75'
      }
    }
  ]
});

// 用于Collapse的活动面板
const activeSeriesKeys = ref<string[]>(['series-0']);

// 处理类目数据（文本形式）
const categoriesText = computed({
  get: () => {
    return localOptions.value.yAxis?.data?.join(',') || '';
  },
  set: (value) => {
    const categories = value.split(',').map((item: string) => item.trim()).filter((item: string) => item);
    localOptions.value.yAxis.data = categories;
    emitUpdate();
  }
});

// 处理系列数据（文本形式）
const seriesDataText = computed(() => {
  return localOptions.value.series.map((series: any) => 
    series.data.join(',')
  );
});

// 更新类目数据
const updateCategories = () => {
  // 类目更新了，可能需要调整每个系列的数据长度
  const categories = localOptions.value.yAxis.data;
  
  // 确保每个系列都有对应数量的数据
  localOptions.value.series.forEach((series: any) => {
    while (series.data.length < categories.length) {
      series.data.push(0);
    }
    while (series.data.length > categories.length) {
      series.data.pop();
    }
  });
  
  emitUpdate();
};

// 更新系列数据
const updateSeriesData = (index: number) => {
  const dataText = seriesDataText.value[index];
  if (dataText !== undefined) {
    const dataArray = dataText.split(',').map((item: string) => {
      const num = parseFloat(item.trim());
      return isNaN(num) ? 0 : num;
    });
    
    // 确保数据长度与类目长度一致
    const categories = localOptions.value.yAxis.data;
    while (dataArray.length < categories.length) {
      dataArray.push(0);
    }
    while (dataArray.length > categories.length) {
      dataArray.pop();
    }
    
    localOptions.value.series[index].data = dataArray;
  }
  
  // 更新图例数据
  const legendData = localOptions.value.series.map((series: any) => series.name);
  localOptions.value.legend.data = legendData;
  
  emitUpdate();
};

// 添加数据系列
const addSeries = () => {
  const newIndex = localOptions.value.series.length;
  const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4'];
  const color = colors[newIndex % colors.length];
  
  // 创建与类目数量相同的数据点
  const categoryCount = localOptions.value.yAxis.data.length;
  const newData = Array(categoryCount).fill(0);
  
  // 创建新系列
  localOptions.value.series.push({
    name: `系列${newIndex + 1}`,
    type: 'bar',
    data: newData,
    label: {
      show: false,
      position: 'right'
    },
    itemStyle: {
      color
    }
  });
  
  // 更新图例数据
  const legendData = localOptions.value.series.map((series: any) => series.name);
  localOptions.value.legend.data = legendData;
  
  // 添加到激活的keys
  activeSeriesKeys.value.push(`series-${newIndex}`);
  
  // 更新系列数据文本
  seriesDataText.value.push(newData.join(','));
  
  emitUpdate();
};

// 移除数据系列
const removeSeries = (index: number) => {
  if (localOptions.value.series.length <= 1) {
    return; // 至少保留一个系列
  }
  
  // 移除系列
  localOptions.value.series.splice(index, 1);
  
  // 更新图例数据
  const legendData = localOptions.value.series.map((series: any) => series.name);
  localOptions.value.legend.data = legendData;
  
  // 更新系列文本
  seriesDataText.value.splice(index, 1);
  
  emitUpdate();
};

// 向父组件发送更新的options
const emitUpdate = () => {
  emit('update:options', { ...localOptions.value });
};

// 初始化
onMounted(() => {
  // 深拷贝props的options
  if (props.options) {
    localOptions.value = JSON.parse(JSON.stringify(props.options));
    
    // 确保必要的属性存在
    if (!localOptions.value.title) {
      localOptions.value.title = { text: '水平条形图' };
    }
    
    if (!localOptions.value.legend) {
      localOptions.value.legend = { show: true, orient: 'horizontal', data: [] };
    }
    
    if (!localOptions.value.grid) {
      localOptions.value.grid = { left: 40, right: 20, bottom: 30, top: 60 };
    }
    
    if (!localOptions.value.xAxis) {
      localOptions.value.xAxis = { type: 'value', name: '数值' };
    }
    
    if (!localOptions.value.yAxis) {
      localOptions.value.yAxis = { 
        type: 'category', 
        name: '类目',
        data: ['类目1', '类目2', '类目3', '类目4', '类目5']
      };
    }
    
    if (!localOptions.value.series || !localOptions.value.series.length) {
      localOptions.value.series = [{
        name: '系列1',
        type: 'bar',
        data: [10, 20, 30, 40, 50],
        label: { show: false, position: 'right' },
        itemStyle: { color: '#5470c6' }
      }];
    } else {
      // 确保每个系列都是bar类型
      localOptions.value.series.forEach((series: any) => {
        series.type = 'bar';
        
        // 确保其他必要属性存在
        if (!series.label) series.label = { show: false, position: 'right' };
        if (!series.itemStyle) series.itemStyle = { color: '#5470c6' };
      });
    }
    
    // 确保图例数据与系列名称同步
    localOptions.value.legend.data = localOptions.value.series.map((series: any) => series.name);
  }
});

// 监听props.options变化
watch(() => props.options, (newOptions) => {
  if (newOptions) {
    localOptions.value = JSON.parse(JSON.stringify(newOptions));
    
    // 确保图例数据与系列名称同步
    if (localOptions.value.legend && localOptions.value.series) {
      localOptions.value.legend.data = localOptions.value.series.map((series: any) => series.name);
    }
  }
}, { deep: true });
</script>

<style scoped>
.chart-settings-container {
  padding: 16px;
}
</style> 